package com.yhos.platform.oopston.core.validator;

import com.yhos.platform.oopston.core.annotation.NotNullValid;
import com.yhos.platform.oopston.core.exception.BusinessException;
import com.yhos.platform.oopston.core.utils.ListUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

public class NotNullValidator extends ConstraintValidator<NotNullValid, Object> {

    private String code;

    @Override
    public void initialize(NotNullValid constraintAnnotation) {
        code = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(Object value) {
        if (value == null) {
            throw new BusinessException(code, code);
        }
        if (value instanceof String) {
            if (StringUtils.isBlank(value.toString())) {
                throw new BusinessException(code, code);
            }
        } else if (value instanceof List) {
            if (ListUtils.isEmpty((List) value)) {
                throw new BusinessException(code, code);
            }
        } else if (value instanceof Map) {
            if (MapUtils.isEmpty((Map) value)) {
                throw new BusinessException(code, code);
            }
        }
        return true;
    }
}
